package com.yunxi.service.dubboService.impl.otd;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yunxi.core.web.ApiResult;
import com.yunxi.core.web.ResponseUtil;
import com.yunxi.model.otd.OtdOrderSo;
import com.yunxi.otd.pojo.OtdOrderScheduleQueryVO;
import com.yunxi.otd.pojo.OtdOrderSoEditVO;
import com.yunxi.otd.service.OtdOrderSoDubboService;
import com.yunxi.service.localService.CodeCreateService;
import com.yunxi.service.localService.VehicleProductViewService;
import com.yunxi.service.localService.otd.OtdInterfaceConfigService;
import com.yunxi.service.localService.otd.OtdOrderSoService;
import java.util.Date;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

public class OtdOrderSoDubboServiceImpl implements OtdOrderSoDubboService {

    private static final Logger logger = LoggerFactory.getLogger(OtdOrderSoDubboServiceImpl.class);

    @Autowired
    @Qualifier("otdOrderSoServiceImpl")
    OtdOrderSoService soService;

    @Autowired
    @Qualifier("otdInterfaceConfigServiceImpl")
    OtdInterfaceConfigService interfaceConfigService;

//    @Autowired
//    private EaiLogBizToHubService eaiLogBizToHubServiceImpl;

    @Autowired
    @Qualifier("vehicleProductViewServiceImpl")
    VehicleProductViewService productService;

    @Autowired
    @Qualifier("codeCreateServiceImpl")
    CodeCreateService code;

    @Override
    public ApiResult findSoSchedule(OtdOrderScheduleQueryVO queryVO) {
        return ResponseUtil.ok(soService.findSoOrderSchedule(queryVO));
    }


    /**
     * SO排产订单接口下发
     *
     * @param orderType 订单类型
     * @param startDate 需求日期起
     * @param endDate 需求日期止
     * @return JSON
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String sendSoOrder(String orderType, Date startDate, Date endDate) {
        logger.info("SO排产订单接口下发开始，订单类型" + orderType);
        // 查询待发送接口数据
        List<OtdOrderSo> orderList = soService.findSendOrderSo(orderType, startDate, endDate);
        if (CollectionUtils.isEmpty(orderList)) {
            return null;
        }
        String json = soService.generateSapJson(orderList);
        logger.info("周计划接口下发，JSON:\n" + json);
        return json;
    }

    /**
     * SO订单日排程修改数量
     *
     * @param editVO 编辑VO
     * @return ApiResult
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResult updateSoOrderNum(OtdOrderSoEditVO editVO) {
        //// =======1.判断日期是否能修改数量
        // TODO


        //// =======2.查询修改前数量
        QueryWrapper<OtdOrderSo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("DEMAND_DATE", editVO.getDemandDate());//需求日期
        queryWrapper.eq("PRODUCT_CODE", editVO.getProductCode());//产品编码
        if (StringUtils.isEmpty(editVO.getCustomPackCode())) {
            queryWrapper.isNull("CUSTOM_PACK_CODE");//选装包
        } else {
            queryWrapper.eq("CUSTOM_PACK_CODE", editVO.getCustomPackCode());//选装包
        }
        queryWrapper.eq("WORKS", editVO.getWorks());//工厂
        queryWrapper.eq("ORDER_TYPE", editVO.getOrderType());//订单类型
        int oldNum = soService.count(queryWrapper);
        //// ========3.判断差异，增加数量还是减少数量
        int diffNum = editVO.getNum() - oldNum;
        if (diffNum == 0) {
            return ResponseUtil.ok();
        } else if (diffNum > 0) {
            logger.info("新增SO订单，产品编码：" + editVO.getProductCode() + "选装：" + editVO.getProductCode() + "，数量：" + diffNum);
            ////新增SO订单
            for (int i = 0; i < diffNum; i++) {
                OtdOrderSo order = new OtdOrderSo();
                order.setPlanNo(code.createCode("P", "yyMMdd", 5));
                order.setProductCode(editVO.getProductCode());
                order.setCustomPackCode(editVO.getCustomPackCode());
                order.setCarName(soService.generateCarName(editVO.getProductCode(), editVO.getCustomPackCode()));
                order.setOrderType(editVO.getOrderType());
                order.setInterfaceType("I");
                order.setDemandDate(editVO.getDemandDate());
                order.setCarLimitState(0);
                order.setLockFlag("");
                order.setWorks(editVO.getWorks());
                order.setSapState("N"); //新建
                soService.save(order);
            }
        } else {
            ////删除指定日期指定数量的SO需求
            soService
                .deleteOverSoOrderByDay(editVO.getDemandDate(), editVO.getProductCode(), editVO.getCustomPackCode(),
                    editVO.getWorks(), editVO.getOrderType(), Math.abs(diffNum));
        }
        return ResponseUtil.ok();
    }

    /**
     *  获取不可编辑的日期
     * @param yearMonth 年月
     * @return ApiResult
     */
    @Override
    public ApiResult getNoEditDays(String yearMonth) {
        return ResponseUtil.ok(interfaceConfigService.findAlreadySendDayList(yearMonth, "SO"));
    }
}
